<template>
  <PageWrapper contentBackground contentClass="flex" dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleReloadCurrent"> 刷新当前页 </a-button>
        <a-button type="primary" @click="handleReload"> 刷新并返回第一页 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <a @click="openDetail(record)">{{ record.name }}</a>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '删除',
                popConfirm: {
                  title: '是否删除？',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <DrawerMessageDetail @register="registerMessageDetail" @call-parent-save-suc="saveSuc" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, BasicColumn, TableAction } from '@/components/Table';
  import { PageWrapper } from '@/components/Page';
  import { useDrawer } from '@/components/Drawer';
  import DrawerMessageDetail from './messageDetail.vue';
  import { messageListApi, messageDeleteApi } from '@/api/message/message';

  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  const [registerMessageDetail, { openDrawer: openDrawer, closeDrawer: closeDrawer }] = useDrawer();

  function openDetail(data) {
    openDrawer(true, data && data.id ? data.id : -1);
  }

  function saveSuc() {
    handleReloadCurrent();
    closeDrawer();
  }

  const [registerTable, { reload }] = useTable({
    title: '加载消息',
    api: messageListApi,
    columns: getBasicColumns(),
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
    },
    pagination: { pageSize: 10 },
  });
  function handleReloadCurrent() {
    reload();
  }

  function getBasicColumns(): BasicColumn[] {
    return [
      {
        title: '姓名',
        dataIndex: 'name',
        fixed: 'left',
      },
      {
        title: '编号',
        dataIndex: 'id',
      },
      {
        title: '联系方式',
        dataIndex: 'phone',
      },
      {
        title: 'ip',
        dataIndex: 'ip',
      },
      {
        title: '创建时间',
        sorter: true,
        dataIndex: 'createTime',
      },
      {
        title: '内容',
        dataIndex: 'content',
      },
    ];
  }

  function handleReload() {
    reload({ page: 1 });
  }
  function handleDelete(record: Recordable) {
    messageDeleteApi(record).then((data: number) => {
      if (data && data > 0) {
        createMessage.success('消息已被删除');
        handleReloadCurrent();
      }
    });
  }
</script>
